<?php

require_once dirname(__FILE__) . '/config.php';
require_once 'functions/sql.php';
$sql = new sql();
$sql->connect();
// Set up the IPP instance
$IPP = new QuickBooks_IPP($dsn);
// Get our OAuth credentials from the database
$creds = $IntuitAnywhere->load($the_username, $the_tenant);

// Tell the framework to load some data from the OAuth store
$IPP->authMode(
        QuickBooks_IPP::AUTHMODE_OAUTH, $the_username, $creds);

// This is our current realm
$realm = $creds['qb_realm'];

// Load the OAuth information from the database
if ($Context = $IPP->context()) {
    // Set the IPP version to v3 
    $IPP->version(QuickBooks_IPP_IDS::VERSION_3);

    $ItemService = new QuickBooks_IPP_Service_Item();
    $SalesReceiptService = new QuickBooks_IPP_Service_SalesReceipt();
    $SalesReceipt = new QuickBooks_IPP_Object_SalesReceipt();

    $SalesReceipt->setDocNumber($lastpaymentid);
    $SalesReceipt->setTxnDate(date('Y-m-d h:i:s'));
    $SalesReceipt->setPaymentRefNum($transaction_id);
    $SalesReceipt->setPaymentMethodRef('3'/* $quickbook_ref_id */);


    $Billemail = new QuickBooks_IPP_Object_BillEmail();
    $Billemail->setEmailStatus('NeedToSend');
    //$Billemail->setIsToBeEmailed(true);
    $Billemail->setAddress($user_email);



    $count = count($_SESSION['shoping_cart']);
    foreach ($_SESSION['shoping_cart'] as $key => $value) {
        $Item = new QuickBooks_IPP_Object_Item();
        $product_name = $value['prd_shortdesc'] . "[" . $value['prd_code'] . "]";
        $Item->setName($product_name);
        $Item->setDescription($value['prd_name']);
        $Item->setIncomeAccountRef('49');
        $Item->setUnitPrice($value['prd_price']);

        $items = $ItemService->query($Context, $realm, "SELECT * FROM Item WHERE Name = '" . $product_name . "' ");

        //$Item = $items[0];
	
	// Update the name of the item
	//$Item->setName($Item->getName() . ' ' . mt_rand(0, 1000));
	
        
        $quick_book_id = '';
        if (count($items) > 0) {
            foreach ($items as $Item) {
                $quick_book_id = $Item->getId();
                $Item->setDescription($value['prd_name']);
                $Item->setUnitPrice($value['prd_price']);
                $updateresp = $ItemService->update($Context, $realm, $Item->getId(), $Item);
            }
        }


        //$Item->setType('Inventory');
        //$Item->setIncomeAccountRef('53');
        if ($quick_book_id != '') {
            $resp = $quick_book_id;
        } else {
            $resp = $ItemService->add($Context, $realm, $Item);
        }
        //echo $resp;exit;
        if ($resp) {
            $product_id = $resp;
            $updatedata = array(
                "quick_book_id" => $product_id,
            );
            $update = $sql->update('tbl_product', $updatedata, array("prd_id" => $value['prd_id']));

            $Line = new QuickBooks_IPP_Object_Line();
            $Line->setDetailType('SalesItemLineDetail');
            $Line->setAmount($value['prd_price'] * $value['prd_qty']);
            $Line->setDescription($value['prd_name']);

            $SalesItemLineDetail = new QuickBooks_IPP_Object_SalesItemLineDetail();
            
            $SalesItemLineDetail->setItemRef($resp);
            //$SalesItemLineDetail->setEmailStatus('test@gmail.com');
            $SalesItemLineDetail->setUnitPrice($value['prd_price']);
            $SalesItemLineDetail->setQty($value['prd_qty']);
		//	$SalesItemLineDetail->setServiceDate(date('Y-m-d', strtotime("+1 day")));

            //$servicedate = date('Y-m-d');
            
            //$jamesDate = date('22/09/2014');
           // $mtDate = date('Y-m-d');
            //$jamesDate = date($mtDate);
            //$SalesItemLineDetail->setServiceDate($servicedate);
            //$SalesItemLineDetail->setServiceDate('22-09-2014');

            $Line->addSalesItemLineDetail($SalesItemLineDetail);

            $SalesReceipt->addLine($Line);
            $SalesReceipt->addBillEmail($Billemail);
            $SalesReceipt->setCustomerRef($last_quickbook_id);
            
        } else {
            print($ItemService->lastError($Context));
        }
    }
    if ($resp = $SalesReceiptService->add($Context, $realm, $SalesReceipt)) {
        // print('Our new SalesReceiptService ID is: [' . $resp . ']');
        unset($_SESSION['shoping_cart']);
        header("Location: " . URL . "thankyou");
    } else {
        die($SalesReceiptService->lastError());
    }
} else {
    die('Unable to load a context...?');
}
?>
